package com.yx.cloud.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.iot.base.service.req.LoginParam;
import com.iot.sweeper.AppContext;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yx.cloud.R;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.utils.SharedPrefsUtil;

import org.json.JSONObject;

import java.net.URLEncoder;

import cz.msebera.android.httpclient.Header;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private static String TAG = "WXEntryActivity";

    private IWXAPI api;
    private BaseResp resp = null;
    private String WX_APP_ID = "wx10ab7c198ba5a2cd";
    // 获取第一步的code后，请求以下链接获取access_token
    private String GetCodeRequest = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    // 获取用户个人信息
    private String GetUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
    private String WX_APP_SECRET = "e3ed514c289da7de927f78f873797221";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "WXEntryActivity ------ ");
//        String packageName = AppUtil.getPackageName(this);
//        if ("com.inxni.robot".equals(packageName)) {
//            api = WXAPIFactory.createWXAPI(this, Constants.WECHAT_APP_ID_INXNI, false);
//            api.handleIntent(getIntent(), this);
//        } else {
//            api = WXAPIFactory.createWXAPI(this, Constants.WECHAT_APP_ID, false);
//            api.handleIntent(getIntent(), this);
//        }
        api = WXAPIFactory.createWXAPI(this, Constants.WECHAT_APP_ID, false);
        api.handleIntent(getIntent(), this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {

        finish();
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        String result = "";
        if (resp != null) {
            resp = resp;
        }

        Log.d(TAG, resp.errCode + ":   BaseResp ------ " + BaseResp.ErrCode.ERR_OK);

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                Log.d(TAG, "ERR_OK ------ " + BaseResp.ErrCode.ERR_OK);
                result = getString(R.string.Sent_successfully);
                Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                String code = ((SendAuth.Resp) resp).code;
                Log.d(TAG, "code ------ " + code);
                String contryCode = SharedPrefsUtil.getValue(this, Constants.CONTRYCODE, "contryCode", "");
                //getUserInfo();
                //涂鸦微信登录接口
                LoginParam param = new LoginParam();
                param.setLoginType(3);
                param.setCountryCode(contryCode);
                param.setCode(code);
                AppContext.getAccountService().login(param);

                /*
                 * 将你前面得到的AppID、AppSecret、code，拼接成URL 获取access_token等等的信息(微信)
                 */
           /*
             获取个人信息,不需要
             String get_access_token = getCodeRequest(code);
                AsyncHttpClient client = new AsyncHttpClient();
                client.post(get_access_token, new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            if (!response.equals("")) {
                                String access_token = response
                                        .getString("access_token");
                                String openid = response.getString("openid");
                                String get_user_info_url = getUserInfo(access_token, openid);
                                getUserInfo(get_user_info_url);
                            }

                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });*/
                finish();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = getString(R.string.send_cancel);
                Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                finish();
                break;
            case BaseResp.ErrCode.ERR_COMM:
                Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = getString(R.string.send_rejected);
                Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                finish();
                break;
            default:
                result = getString(R.string.send_back);
                Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                finish();
                break;
        }
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent(Event event) {
//        if (event.getType() == event.MESSAGE_TYPE_LOGIN) {
//            if (event.isResult()) {
//                Log.d(TAG, "微信登录 Success: ");
//                SharedPrefsUtil.putValue(this, Constants.USERNAME, "username", "WeChat");
//                //保存user,给Ld使用
//                Intent_utils.enterIntent(WXEntryActivity.this, MainActivity.class);
//                finish();
//            } else {
//                Toast.makeText(this, event.getContent() + "", Toast.LENGTH_LONG).show();
//                finish();
//            }
//        }
//    }

    /**
     * 通过拼接的用户信息url获取用户信息
     *
     * @param user_info_url
     */
    private void getUserInfo(String user_info_url) {
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(user_info_url, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, headers, response);
                try {

                    System.out.println("获取用户信息:" + response);

                    if (!response.equals("")) {
                        String openid = response.getString("openid");
                        String nickname = response.getString("nickname");
                        String headimgurl = response.getString("headimgurl");
                        Log.d(TAG, "openid : " + openid);
                        Log.d(TAG, "nickname : " + nickname);
                        Log.d(TAG, "headimgurl : " + headimgurl);
                    }

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
        // finish();
    }

    /**
     * 获取access_token的URL（微信）
     *
     * @param code 授权时，微信回调给的
     * @return URL
     */
    private String getCodeRequest(String code) {
        String result = null;
        GetCodeRequest = GetCodeRequest.replace("APPID",
                urlEnodeUTF8(Constants.WECHAT_APP_ID));
        GetCodeRequest = GetCodeRequest.replace("SECRET",
                urlEnodeUTF8(Constants.WECHAT_APP_SECRET));
        GetCodeRequest = GetCodeRequest.replace("CODE", urlEnodeUTF8(code));
        result = GetCodeRequest;
        return result;
    }

    /**
     * 获取用户个人信息的URL（微信）
     *
     * @param access_token 获取access_token时给的
     * @param openid       获取access_token时给的
     * @return URL
     */
    private String getUserInfo(String access_token, String openid) {
        String result = null;
        GetUserInfo = GetUserInfo.replace("ACCESS_TOKEN",
                urlEnodeUTF8(access_token));
        GetUserInfo = GetUserInfo.replace("OPENID", urlEnodeUTF8(openid));
        result = GetUserInfo;
        return result;
    }

    private String urlEnodeUTF8(String str) {
        String result = str;
        try {
            result = URLEncoder.encode(str, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        EventBus.getDefault().register(this);
//    }
//
//    @Override
//    protected void onPause() {
//        super.onPause();
//        EventBus.getDefault().unregister(this);
//    }

}